<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    @close="dialogFormVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form size="" ref="formRef" :model="form" label-width="200px">
      <el-form-item label="设为顶级">
        <el-button type="primary" @click="setTop">设为顶级会员</el-button>
      </el-form-item>
      <el-form-item label="搜索上级">
        <el-select
          v-model="form.referee_id"
          filterable
          remote
          placeholder="输入用户ID/昵称/姓名/手机号进行搜索"
          remote-show-suffix
          :remote-method="searchUser"
          :loading="search_loading"
          default-first-option
        >
          <el-option
            v-for="item in userOptions"
            :key="item.user_id"
            :label="item.real_name ? item.real_name : item.nickName"
            :value="item.user_id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelFunc">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getUserOption, setReferee } from "@/api/user";
import { ElMessage } from "element-plus";
import { ref } from "vue";
const title = ref("修改上级");
const dialogVisible = ref(false);
const form = ref({
  user_id: [] as number[],
  referee_id: "",
});
const setRows = ref<any[]>([]);
const formRef = ref<any>(null);
const loading = ref(false);
const search_loading = ref(false);
const userOptions = ref<any[]>([]);
const dialogFormVisible = () => {
  dialogVisible.value = false;
};
const open = (users: any[]) => {
  setRows.value = users;
  const id = users.map((item) => item.user_id);
  const names = users.map((item) =>
    item.real_name ? item.real_name : item.nickName
  );
  let show_names = names.join(",").substring(0, 20) + "...";
  if (id.length == 1) {
    title.value = "设置上级（" + names[0] + "）";
  } else {
    title.value = "批量设置上级（" + show_names + "）";
  }
  dialogVisible.value = true;
  form.value.user_id = id;
};
const searchUser = (query: string) => {
  if (query !== "") {
    search_loading.value = true;
    getUserOption({
      keyword: query,
    }).then((res: any) => {
      if (res.code == 1) {
        userOptions.value = res.data;
        search_loading.value = false;
      }
    });
  } else {
    userOptions.value = [];
  }
};

const emits = defineEmits(["doneSave"]);
const onSubmit = () => {
  setReferee(form.value)
    .then((data: any) => {
      ElMessage({
        message: "设置成功",
        type: "success",
      });
      loading.value = false;
      dialogFormVisible();
      emits("doneSave");
    })
    .catch((error) => {
      loading.value = false;
    });
};
const setTop = () => {
  form.value.referee_id = "0";
  onSubmit();
};
/*取消*/
const cancelFunc = () => {
  dialogFormVisible();
};
defineExpose({ open });
</script>

<style></style>
